<template>
  <CommonPage>
    <template #action>
      <NButton type="primary" @click="handleAdd()">
        <i class="i-material-symbols:add mr-4 text-18" />
        新增角色
      </NButton>
    </template>

    <MeCrud
      ref="$table"
      v-model:query-items="queryItems"
      :scroll-x="1200"
      :columns="columns"
      :get-data="api.read"
    >
      <MeQueryItem label="角色名" :label-width="50">
        <n-input v-model:value="queryItems.name" type="text" placeholder="请输入角色名" clearable />
      </MeQueryItem>
      <MeQueryItem label="编码" :label-width="50">
        <n-input v-model:value="queryItems.code" type="text" placeholder="请输入角色编码" clearable />
      </MeQueryItem>
      <MeQueryItem label="状态" :label-width="50">
        <n-select v-model:value="queryItems.status" clearable :options="DATA_STATUS" />
      </MeQueryItem>
    </MeCrud>
    <MeModal ref="modalRef" width="520px">
      <n-form
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
      >
        <n-form-item
          label="角色名"
          path="name"
          :rule="{
            required: true,
            message: '请输入角色名',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.name" />
        </n-form-item>
        <n-form-item
          label="角色编码"
          path="code"
          :rule="{
            required: true,
            message: '请输入角色编码',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.code" :disabled="modalAction !== 'add'" />
        </n-form-item>
        <n-form-item label="状态" path="enable">
          <NSwitch v-model:value="modalForm.status" checked-value="0" unchecked-value="1">
            <template #checked>
              启用
            </template>
            <template #unchecked>
              停用
            </template>
          </NSwitch>
        </n-form-item>
        <n-form-item
          label="排序"
          path="sort"
          :rule="{
            required: true,
            type: 'number',
            message: '请输入排序',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input-number v-model:value="modalForm.sort" :min="0" clearable />
        </n-form-item>
        <n-form-item
          label="备注"
          path="remark"
        >
          <n-input v-model:value="modalForm.remark" type="textarea" />
        </n-form-item>
      </n-form>
    </MeModal>

    <PermissionAddOrEdit ref="permissionAddOrEditRef" :menu-tree="menuTree" />
  </CommonPage>
</template>

<script setup>
import { CommonPage, MeCrud, MeModal, MeQueryItem } from '@/components'
import { useCrud } from '@/composables'
import { NButton, NSwitch, NTag } from 'naive-ui'
import { useTemplateRef } from 'vue'
import menuApi from '../menu/api'
import api from './api'
import PermissionAddOrEdit from './components/PermissionAddOrEdit.vue'

defineOptions({ name: 'RoleList' })

const $table = useTemplateRef('$table')

// 状态字典-> 数据状态
const { DATA_STATUS } = $dict('DATA_STATUS')

/** QueryBar筛选参数（可选） */
const queryItems = ref({})

onMounted(() => {
  $table.value?.handleSearch()
})

const { modalRef, modalFormRef, modalAction, modalForm, handleAdd, handleDelete, handleEdit }
  = useCrud({
    name: '角色',
    doCreate: api.create,
    doDelete: api.delete,
    doUpdate: api.update,
    initForm: { status: '0', sort: 0 },
    refresh: (_, keepCurrentPage) => $table.value?.handleSearch(keepCurrentPage),
  })

const columns = [
  { title: '角色名', key: 'name' },
  { title: '角色编码', key: 'code' },
  {
    title: '状态',
    key: 'status',
    render: row =>
      h(
        NTag,
        {
          size: 'small',
          type: row.status === '0' ? 'success' : 'warning',
        },
        {
          default: () => row.status === '0' ? '启用' : '停用',
        },
      ),
  },
  { title: '备注', key: 'remark' },
  { title: '创建时间', key: 'created_at' },
  { title: '排序', key: 'sort' },
  {
    title: '操作',
    key: 'actions',
    width: 320,
    align: 'right',
    fixed: 'right',
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            text: true,
            type: 'primary',
            loading: !!row.loading,
            onClick: () => handleAssignPermissions(row),
          },
          {
            default: () => '分配权限',
            icon: () => h('i', { class: 'i-fe:slack text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            text: true,
            type: 'primary',
            style: 'margin-left: 12px;',
            onClick: () => handleEdit(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-material-symbols:edit-outline text-14' }),
          },
        ),

        h(
          NButton,
          {
            size: 'small',
            text: true,
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row.id, row.name),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },
]

const permissionAddOrEditRef = useTemplateRef('permissionAddOrEditRef')
async function handleAssignPermissions(row) {
  row.loading = true
  try {
    const { data } = await api.getRolePermissions({ id: row.id })
    permissionAddOrEditRef.value?.handleOpen({
      title: '分配权限',
      width: '400px',
      row: { id: row.id, menu_ids: data },
      okText: '保存',
    })
  }
  finally {
    row.loading = false
  }
}

const menuTree = ref([])
menuApi.getAllPermissionTree().then(({ data = [] }) => (menuTree.value = data))
</script>
